//
//  MyPublic_EditVC.m
//  MZJ
//
//  Created by XDD on 16/6/16.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "MyPublic_EditVC.h"
#import "MyPublic_view.h"
#import "TZImagePickerController.h"
#import "CoverCell.h"
#import "UploadPicView.h"
#import "AFNetworking.h"

#define imageWith 600

@interface MyPublic_EditVC () <UITextViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,TZImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDelegate,UIImagePickerControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource> {
    BOOL isStopUpload_; //是否停止上传
    NSString *uimageStr;
    UIView *Mbview;
    UIView *tankuangView;
    UITextField *yjTextFiled;
    NSMutableArray *selectedAssets_;
    NSInteger stepTimes_;
    UIImage *originalImage;
    CGSize  ssss;
    NSMutableArray *img_Arr;
    NSArray *arr;
    NSString *town_tid_Str;
}

@property (nonatomic, strong)  NSMutableArray *nameArr;//镇名DEMO


@property (nonatomic, strong) MyPublic_view *myPublic_view;
@property (nonatomic, assign)  BOOL chooseNeeds_money;//选择资金判断
@property (nonatomic, strong) NSString *choose_Sex;//判断性别
@property (nonatomic, strong) NSString *choose_type;//判断困难类型
@property (nonatomic, assign) BOOL chooseNeeds_goods;//选择物资判断
@property (nonatomic, strong) NSString *choose_detail_fund;//判断需求资金
@property (nonatomic, strong) NSString *choose_detail_goods;//判断需求物资

@property (nonatomic, strong) UICollectionView *coverCollectView;
@property (nonatomic, strong) NetWorkingSModel *model;
@property (nonatomic, strong) UIView *keyBoardView;
@property (nonatomic, strong) UploadPicView *uploadView;
//@property (nonatomic, strong) DraftAlertView *alertView; //返回提示框
@property (nonatomic, assign) NSInteger currentIndex; //正在上传的当前图片
@property (nonatomic, strong) NSTimer *timer; //添加计时器，如果超过20秒还没有上传成功，就停止上传，并提示可重新上传
//@property (nonatomic, strong) UIView *viewPic; //添加图片弹框
@property (nonatomic, strong) TZImagePickerController *imagePicker;
@property (nonatomic, strong) NSMutableArray *seletedPhotos;
@property (nonatomic, strong)UIPickerView *pickerView;
@property (nonatomic, strong)UIButton *querenBt;
@property (nonatomic, strong)UIView *mengbanView;
@property (nonatomic, strong)UIView *mBView;
@property (nonatomic, strong)UIButton *quxiaoBt;
@property (nonatomic, strong)UIView *pickerAddView;

@end

@implementation MyPublic_EditVC
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
   
    NSLog(@"myPublic_EditVC dealloc");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    
    self.myPublic_view.hidden = NO;
    _nameArr = [NSMutableArray array];
//    _nameArr = @[@"基本资料",@"我的求助",@"我的救助",@"我的志愿者活动",@"我的回复",@"系统提醒",@"设置"];

    
    
    UIButton *submit_Btn = [UIButton buttonWithType:UIButtonTypeCustom];
    submit_Btn.frame = CGRectMake(kWidth - 45, 25, 35, 25);
    [submit_Btn setTitle:@"提交" forState:UIControlStateNormal];
    [submit_Btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submit_Btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [submit_Btn addTarget:self action:@selector(submit_BtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.topBar addSubview:submit_Btn];
    

    self.seletedPhotos = [NSMutableArray array];
    img_Arr = [NSMutableArray array];

    //UIPickerView的初始化
    self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 160)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    self.pickerView.showsSelectionIndicator = YES;
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    [layout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    NSInteger collectWidth = screenWith - 20;
    NSInteger cellWidth = (collectWidth - 30)/4.f;
    self.coverCollectView = [[UICollectionView alloc] initWithFrame:CGRectMake(18, 810, collectWidth, cellWidth) collectionViewLayout:layout];
    self.coverCollectView.delegate = self;
    self.coverCollectView.dataSource = self;
    self.coverCollectView.backgroundColor = [UIColor clearColor];
    [self.coverCollectView registerNib:[UINib nibWithNibName:@"CoverCell" bundle:nil] forCellWithReuseIdentifier:@"CoverCell"];
    [_myPublic_view.scrollView addSubview:self.coverCollectView];
    
    //监听键盘弹出与收回
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    //在键盘的顶部加一个uiview
    _keyBoardView = [[UIView alloc] initWithFrame:CGRectMake(0, screenHeight, screenWith, 40)];
    _keyBoardView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_keyBoardView];
    
    UIButton *didButton = [[UIButton alloc] initWithFrame:CGRectMake(screenWith - 50, 0, 50, 40)];
    [didButton setTitle:@"完成" forState:UIControlStateNormal];
    [didButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [didButton addTarget:self action:@selector(didButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_keyBoardView addSubview:didButton];
    
    _mengbanView = [[UIView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 160, [UIScreen mainScreen].bounds.size.width, 160)];
    _mengbanView.backgroundColor = [UIColor whiteColor];
    
    //PickerView上面的view
    _pickerAddView = [[UIView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 195, [UIScreen mainScreen].bounds.size.width, 35)];
    _pickerAddView.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
    
    _quxiaoBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _quxiaoBt.frame = CGRectMake(0, 5, 50, 30);
    [_quxiaoBt setTitle:@"取消" forState:UIControlStateNormal];
    [_quxiaoBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _quxiaoBt.titleLabel.font = [UIFont systemFontOfSize:13];
    [_quxiaoBt addTarget:self action:@selector(quxiaoBtAction) forControlEvents:UIControlEventTouchUpInside];
    
    _querenBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _querenBt.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 50, 5, 50, 30);
    [_querenBt setTitle:@"确认" forState:UIControlStateNormal];
    [_querenBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _querenBt.titleLabel.font = [UIFont systemFontOfSize:13];
    [_querenBt addTarget:self action:@selector(querenBtAction) forControlEvents:UIControlEventTouchUpInside];
    
    [XJNetWorkingManager success_DownAndType:^(id responseObject) {
//        [DataModel object].down_Name_Arr = responseObject[@"result"][@"town"];
        arr = responseObject[@"result"][@"town"];
        for (int i = 0; i < arr.count; i++) {
            [_nameArr addObject:arr[i][@"tname"]];
        }
//        _nameArr = responseObject[@"result"][@"tname"];
        
//        [DataModel object].type_Name_Arr = responseObject[@"result"][@"type"];
        
//        NSLog(@"%@",[DataModel object].down_Name_Arr);
        
    } failureHandler:^(NSError *error) {
        
    }];

}

//点击完成
- (void)didButtonClick:(UIButton *)sender {

    [_myPublic_view.money_textField resignFirstResponder];
    [_myPublic_view.remarks_textField resignFirstResponder];
    [_myPublic_view.ageTextField resignFirstResponder];
    [_myPublic_view.title_TextField resignFirstResponder];
    [_myPublic_view.idCardTextField resignFirstResponder];
    [_myPublic_view.home_address_TextField resignFirstResponder];
    [_myPublic_view.person_Num_TextField resignFirstResponder];
    [_myPublic_view.nameTextField resignFirstResponder];
    [_myPublic_view.phoneNum_TextField resignFirstResponder];
    [_myPublic_view.requirement_textView resignFirstResponder];
}

- (MyPublic_view *)myPublic_view {
    
    if (!_myPublic_view) {
        _myPublic_view = [[MyPublic_view alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:_myPublic_view];
        
        self.topBar.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
        self.titleLabel.text = @"求助资料编辑";
        self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
        [self.backButton setTitle:@"" forState:UIControlStateNormal];
        
        __weak typeof (self)weakSelf = self;
        [_myPublic_view setDidsexBtn_manBlock:^{
            weakSelf.myPublic_view.chooseImageView.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
            weakSelf.myPublic_view.chooseImageView1.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            _choose_Sex = @"1";
        }];
        [_myPublic_view setDidsexBtn_woManBlock:^{
            weakSelf.myPublic_view.chooseImageView.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.chooseImageView1.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
            _choose_Sex = @"2";
        }];
        [_myPublic_view setDidtype_btn1Block:^{
            weakSelf.myPublic_view.typeimageView1.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
            weakSelf.myPublic_view.typeimageView2.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView3.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView4.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView5.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            _choose_type = @"0";
        }];
        [_myPublic_view setDidtype_btn2Block:^{
            weakSelf.myPublic_view.typeimageView1.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView2.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
            weakSelf.myPublic_view.typeimageView3.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView4.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView5.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            _choose_type = @"1";
        }];
        [_myPublic_view setDidtype_btn3Block:^{
            weakSelf.myPublic_view.typeimageView1.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView2.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView3.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
            weakSelf.myPublic_view.typeimageView4.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView5.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            _choose_type = @"2";
        }];
        [_myPublic_view setDidtype_btn4Block:^{
            weakSelf.myPublic_view.typeimageView1.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView2.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView3.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView4.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
            weakSelf.myPublic_view.typeimageView5.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            _choose_type = @"3";
        }];
        [_myPublic_view setDidtype_btn5Block:^{
            weakSelf.myPublic_view.typeimageView1.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView2.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView3.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView4.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.myPublic_view.typeimageView5.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
            _choose_type = @"4";
        }];
        [_myPublic_view setDidfundBtnBlock:^{
            if (weakSelf.chooseNeeds_money) {
                weakSelf.myPublic_view.fundimageView.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
                weakSelf.chooseNeeds_money = NO;
                _choose_detail_fund = @"1";
            } else {
                weakSelf.myPublic_view.fundimageView.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
                weakSelf.chooseNeeds_money = YES;
                _choose_detail_fund = @"0";
            }
        }];
        [_myPublic_view setDidgoodsBtnBlock:^{
            if (weakSelf.chooseNeeds_goods) {
                weakSelf.myPublic_view.goodsimageView.image = [UIImage imageNamed:@"Checked_YES_img@2x"];
                weakSelf.chooseNeeds_goods = NO;
                _choose_detail_goods = @"1";
            } else {
                weakSelf.myPublic_view.goodsimageView.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
                weakSelf.chooseNeeds_goods = YES;
                _choose_detail_goods = @"0";
            }
        }];
        [_myPublic_view setDiddown_chooseBtnBlock:^{
            weakSelf.myPublic_view.chooseDown_TextField.userInteractionEnabled = NO;

            [weakSelf.myPublic_view.money_textField resignFirstResponder];
            [weakSelf.myPublic_view.remarks_textField resignFirstResponder];
            [weakSelf.myPublic_view.ageTextField resignFirstResponder];
            [weakSelf.myPublic_view.title_TextField resignFirstResponder];
            [weakSelf.myPublic_view.idCardTextField resignFirstResponder];
            [weakSelf.myPublic_view.home_address_TextField resignFirstResponder];
            [weakSelf.myPublic_view.person_Num_TextField resignFirstResponder];
            [weakSelf.myPublic_view.nameTextField resignFirstResponder];
            [weakSelf.myPublic_view.phoneNum_TextField resignFirstResponder];
            [weakSelf.myPublic_view.requirement_textView resignFirstResponder];
            
            weakSelf.mBView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
            UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:weakSelf action:@selector(singleTapClickAction:)];
            [weakSelf.mBView addGestureRecognizer:singleTap];
            weakSelf.mBView.backgroundColor = [UIColor clearColor];
            [weakSelf.view addSubview:weakSelf.mBView];
            

            [weakSelf.mBView addSubview:weakSelf.mengbanView];
            [weakSelf.mengbanView addSubview:weakSelf.pickerView];

            [weakSelf.mBView addSubview:weakSelf.pickerAddView];

            [weakSelf.pickerAddView addSubview:weakSelf.querenBt];
            [weakSelf.pickerAddView addSubview:weakSelf.quxiaoBt];
        }];

    }
    return _myPublic_view;
}

- (IBAction)singleTapClickAction:(id)sender {
    _mBView.hidden = YES;
    _myPublic_view.chooseDown_TextField.userInteractionEnabled = YES;
}

//取消按钮
- (void)quxiaoBtAction {
    _mBView.hidden = YES;
    _myPublic_view.chooseDown_TextField.userInteractionEnabled = YES;
}

//确认按钮
- (void)querenBtAction {
    for (int j = 0; j < arr.count; j++) {
        if ([[_nameArr objectAtIndex:[self.pickerView selectedRowInComponent:0]] isEqualToString:arr[j][@"tname"]]) {
            NSLog(@"%@",arr[j][@"tid"]);
            town_tid_Str = arr[j][@"tid"];
        }
    }
    
    
    NSLog(@"%@",[_nameArr objectAtIndex:[self.pickerView selectedRowInComponent:0]]);
    _myPublic_view.chooseDown_TextField.text = [_nameArr objectAtIndex:[self.pickerView selectedRowInComponent:0]];
    _mBView.hidden = YES;
    _myPublic_view.chooseDown_TextField.userInteractionEnabled = YES;
}

//提交资料按钮
- (void)submit_BtnAction {

    NSString *s1 = [NSString stringWithFormat:@"%d",[_myPublic_view.ageTextField.text intValue]];
//    NSString *s3 = [NSString stringWithFormat:@"%d",[_myPublic_view.idCardTextField.text intValue]];
    NSString *s5 = [NSString stringWithFormat:@"%d",[_myPublic_view.person_Num_TextField.text intValue]];
    NSString *s7 = [NSString stringWithFormat:@"%d",[_myPublic_view.phoneNum_TextField.text intValue]];
    if (self.seletedPhotos.count == 0 || [s1 intValue] == 0 || IsNilString(_myPublic_view.title_TextField.text) || IsNilString(_myPublic_view.home_address_TextField.text) || IsNilString(_myPublic_view.nameTextField.text) || [s5 intValue] == 0  || IsNilString(_myPublic_view.idCardTextField.text) || IsNilString(_myPublic_view.nameTextField.text) || [s7 intValue] == 0 || IsNilString(_myPublic_view.requirement_textView.text) || (IsNilString(_myPublic_view.money_textField.text) && IsNilString(_myPublic_view.remarks_textField.text))|| [town_tid_Str intValue] == 0 ) {
        [self waringAction:@"信息不完整!"];

    } else {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"user_token"] forKey:@"token"];

        isStopUpload_ = NO;
        
        [self uploadPicture:dic];
        self.uploadView.hidden = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"nextPic" object:nil userInfo:@{@"index":[NSString stringWithFormat:@"正在上传第%ld张",self.currentIndex+1]}];
        
        //开始上传就打开计时器，上传成功从新开始计时
        [self timerStart];
    }
}

- (void)uploadPicture:(NSMutableDictionary *)dic {
    
    if (!isStopUpload_) {
        
        __weak typeof (self)weakSelf = self;

            AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
            requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];
            requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
            
            [requestManager POST:@"http://192.168.1.254:8004/app/homeapp/publish_helpimg.json" parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                
                originalImage = self.seletedPhotos[weakSelf.currentIndex];
                ssss =  CGSizeFromString(NSStringFromCGSize(originalImage.size));
                NSData *data = UIImageJPEGRepresentation([self scaleToSize:originalImage size:CGSizeMake(imageWith, (imageWith/ssss.width)*ssss.height)], 0.8);
                NSString *name = @"pimimg";
                NSString *filename = @"file.JPEG";
                [formData appendPartWithFileData:data name:name fileName:filename mimeType:@"image/JPEG"];
                
            } success:^(AFHTTPRequestOperation *operation, id responseObject) {
                
                NSDictionary* dict_ = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                
                if ([[dict_ objectForKey:@"statu"] integerValue] == 0) {
                    [img_Arr addObject:dict_[@"result"]];
                    //上传成功
                    if (weakSelf.currentIndex == self.seletedPhotos.count - 1) {
                        
                        //上传完成
                        //图片上传完成开始上传文字描述
                        [weakSelf pubcontentHttp];
                        //                        NSLog(@"上传成功");
                        if (self.timer) {
                            //移除计时器
                            [self.timer invalidate];
                        }
                    }
                    else {
                        //上传下一张
                        self.currentIndex++;
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"nextPic" object:nil userInfo:@{@"index":[NSString stringWithFormat:@"正在上传第%ld张",weakSelf.currentIndex + 1]}];
                        
                        stepTimes_ = 0;
                        [weakSelf uploadPicture:dic];
                    }
                }
                else {
                    
                    //上传失败，重新上传
                    if (stepTimes_ == 30) {
                        
                        //停止上传
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"nextPic" object:nil userInfo:@{@"index":@"上传失败"}];
                        //显示上传失败，在1.0秒后隐藏View
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            
                            self.uploadView.hidden = YES;
                        });
                        isStopUpload_ = YES;
                        stepTimes_ = 0;
                        if (self.timer) {
                            
                            //暂停计时器
                            [self.timer setFireDate:[NSDate distantFuture]];
                        }
                    }
                    [weakSelf uploadPicture:dic];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"nextPic" object:nil userInfo:@{@"index":[NSString stringWithFormat:@"正在上传第%ld张",weakSelf.currentIndex+1]}];
                }
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"nextPic" object:nil userInfo:@{@"index":@"请检查网络"}];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    self.uploadView.hidden = YES;
                    //暂停计时器
                    if (self.timer) {
                        [self.timer setFireDate:[NSDate distantFuture]];
                    }
                });
            }];
        
    }
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, imageWith, (imageWith/ssss.width)*ssss.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

- (void)pubcontentHttp {
    if (!_model) {
        _model = [[NetWorkingSModel alloc] init];
        //            [self person_data_httprequest];
        __weak typeof (self)weakSelf = self;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *token = [user objectForKey:@"user_token"];
        
        if (token.length != 0) {
 
            [dic setObject:token forKey:@"token"];
            [dic setObject:_myPublic_view.nameTextField.text forKey:@"puname"];
            [dic setObject:_choose_Sex forKey:@"pusex"];
            [dic setObject:_myPublic_view.ageTextField.text forKey:@"puage"];
            [dic setObject:_myPublic_view.person_Num_TextField.text forKey:@"punum"];
            [dic setObject:_myPublic_view.phoneNum_TextField.text forKey:@"pumobile"];
            [dic setObject:_myPublic_view.home_address_TextField.text forKey:@"puaddress"];
            [dic setObject:_myPublic_view.idCardTextField.text forKey:@"pucard"];
            [dic setObject:_myPublic_view.title_TextField.text forKey:@"pname"];
            [dic setObject:_myPublic_view.requirement_textView.text forKey:@"pdescription"];
            [dic setObject:town_tid_Str forKey:@"tid"];
//            [dic setObject:_myPublic_view.money_textField.text forKey:@"phopemoney"];
            [dic setObject:_choose_type forKey:@"psort"];
            [dic setObject:img_Arr forKey:@"pimimg"];
            if ([_choose_detail_goods isEqualToString:@"1"]) {
                [dic setObject:_myPublic_view.remarks_textField.text forKey:@"pnote"];
            }
            if ([_choose_detail_fund isEqualToString:@"1"]) {
                [dic setObject:_myPublic_view.money_textField.text forKey:@"phopemoney"];
            }
            
            NSLog(@"%@",_myPublic_view.nameTextField.text);
             NSLog(@"%@",_choose_Sex);
             NSLog(@"%@",_myPublic_view.ageTextField.text);
             NSLog(@"%@",_myPublic_view.person_Num_TextField.text);
             NSLog(@"%@",_myPublic_view.phoneNum_TextField.text);
             NSLog(@"%@",_myPublic_view.home_address_TextField.text);
             NSLog(@"%@",_myPublic_view.idCardTextField.text);
             NSLog(@"%@",_myPublic_view.title_TextField.text);
             NSLog(@"%@",_myPublic_view.requirement_textView.text);
             NSLog(@"%@",_choose_type);
             NSLog(@"物资需求 = %@",_myPublic_view.remarks_textField.text);
             NSLog(@"需求资金 = %@",_myPublic_view.money_textField.text);
            
            
            NSLog(@"dic = %@",dic);
        }
        
        [_model setBlockWithReturnBlock:^(id returnValue) {
            
            NSLog(@"发布需求上传 = %@",returnValue);
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"nextPic" object:nil userInfo:@{@"index":[NSString stringWithFormat:@"%@",[returnValue objectForKey:@"result"]]}];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //延迟1.0秒隐藏view
                weakSelf.uploadView.hidden = YES;
                isStopUpload_ = NO;
                
                weakSelf.tabBarController.tabBar.hidden = YES;
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        } WithErrorBlock:^(id errorCode) {
            
        }];
        [weakSelf.model homeAppGetpublish_help:dic];
        
    }
}

#pragma mark -- 点击发送

- (void)timerStart {
    
    //限定每张图片上传时间为20秒，超过20秒，则认为上传失败，提示网络问题
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(stopUpload:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
}

//停止上传
- (void)stopUpload:(NSTimer *)sender {
    
    stepTimes_ += 1;
    if (stepTimes_ == 30) {
        //停止上传
        [[NSNotificationCenter defaultCenter] postNotificationName:@"nextPic" object:nil userInfo:@{@"index":@"上传失败"}];
        //显示上传失败，在1.0秒后隐藏View
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            self.uploadView.hidden = YES;
            //暂停计时器
            if (self.timer) {
                [self.timer setFireDate:[NSDate distantFuture]];
            }
            
        });
    }
}

- (UploadPicView *)uploadView {
    
    if (!_uploadView) {
        _uploadView = [[UploadPicView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:_uploadView];
    }
    return _uploadView;
}

//点击返回键
- (void)clickedBackButton:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSValue *keyboardFrameValue = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardTop = keyboardFrameValue.CGRectValue.origin.y;
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    // 获取必要信息
    if (_myPublic_view.money_textField.isEditing || _myPublic_view.remarks_textField.isEditing) {
        
        // 添加移动动画，使视图跟随键盘移动
        [UIView animateWithDuration:duration animations:^{
            [UIView setAnimationBeginsFromCurrentState:YES];
            [UIView setAnimationCurve:curve];
            CGRect frame = _myPublic_view.scrollView.frame;
            frame = CGRectMake(0, keyboardTop - frame.size.height-20, self.view.frame.size.width, frame.size.height);
            _myPublic_view.scrollView.frame = frame;
        }];
    }
    
    [UIView animateWithDuration:duration animations:^{
        
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:curve];
        CGRect frame = _keyBoardView.frame;
        frame = CGRectMake(0, keyboardTop - frame.size.height, self.view.frame.size.width, frame.size.height);
        _keyBoardView.frame = frame;
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    // 获取必要信息
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    // 添加移动动画，使视图跟随键盘移动
    [UIView animateWithDuration:duration animations:^{
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:curve];
        CGRect frame = _myPublic_view.scrollView.frame;
        frame.origin.y = 55;
        _myPublic_view.scrollView.frame = frame;
    }];
    
    [UIView animateWithDuration:duration animations:^{
        
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationCurve:curve];
        CGRect frame = _keyBoardView.frame;
        frame.origin.y = self.view.frame.size.height;
        _keyBoardView.frame = frame;
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
}

#pragma mark -- collectionView,delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.seletedPhotos.count + 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CoverCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CoverCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[CoverCell alloc] initWithFrame:CGRectZero];
    }
    cell.backgroundColor = [UIColor clearColor];
    if (indexPath.row == self.seletedPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"AlbumAddBtn"];
        cell.deleteButton.hidden = YES;
    }else {
        cell.imageView.image = self.seletedPhotos[indexPath.row];
        cell.deleteButton.hidden = NO;
    }
    
    //点击删除
    __weak typeof (self)weakSelf = self;
    [cell setDidClickDeleteButton:^(CoverCell *coverCell) {
        
        NSIndexPath *indexPath = [self.coverCollectView indexPathForCell:coverCell];
        [weakSelf.seletedPhotos removeObjectAtIndex:indexPath.item];
        [weakSelf.coverCollectView deleteItemsAtIndexPaths:@[indexPath]];
        if (self.seletedPhotos.count <= 3) {
            
//            [self.coverCollectView setFrame:CGRectMake(18, 810, collectWidth, cellWidth*2 + 10)];
            [_myPublic_view.scrollView setContentSize:CGSizeMake(kWidth, 1180)];
            
            _myPublic_view.type_view.frame = CGRectMake(5, 910, kWidth - 10, 100);
            _myPublic_view.view3.frame = CGRectMake(10, 1027, 3, 13);
            _myPublic_view.require_detail_Label.frame = CGRectMake(18, 1020, 100, 25);
            _myPublic_view.fundBtn.frame = CGRectMake(18, 1075, 50, 20);
            _myPublic_view.money_Label.frame = CGRectMake(120, 1075, 30, 25);
            _myPublic_view.money_textField.frame = CGRectMake(155, 1080, kWidth - 155 - 20, 15);
            _myPublic_view.goodsBtn.frame = CGRectMake(18, 1115, 50, 20);
            _myPublic_view.remarks_Label.frame = CGRectMake(120, 1115, 30, 25);
            _myPublic_view.remarks_textField.frame = CGRectMake(155, 1120, kWidth - 155 - 20, 15);
            
        }
    }];
    
    NSInteger collectWidth = screenWith - 20;
    NSInteger cellWidth = (collectWidth - 30)/4.f;
    if (self.seletedPhotos.count > 3) {
        
        [self.coverCollectView setFrame:CGRectMake(18, 810, collectWidth, cellWidth*2 + 10)];
        [_myPublic_view.scrollView setContentSize:CGSizeMake(kWidth, 1280)];
//5, 910, kWidth - 10, 100
        _myPublic_view.type_view.frame = CGRectMake(5, CGRectGetMaxY(self.coverCollectView.frame) + 22, kWidth - 10, 100);
        _myPublic_view.view3.frame = CGRectMake(10, CGRectGetMaxY(self.coverCollectView.frame) + 137, 3, 13);
        _myPublic_view.require_detail_Label.frame = CGRectMake(18, CGRectGetMaxY(self.coverCollectView.frame) + 135, kWidth, 20);
        _myPublic_view.fundBtn.frame = CGRectMake(18, CGRectGetMaxY(self.coverCollectView.frame) + 180, 50, 20);
        _myPublic_view.money_Label.frame = CGRectMake(120, CGRectGetMaxY(self.coverCollectView.frame) + 180, 30, 25);
        _myPublic_view.money_textField.frame = CGRectMake(155, CGRectGetMaxY(self.coverCollectView.frame) + 185, kWidth - 155 - 20, 15);
        _myPublic_view.goodsBtn.frame = CGRectMake(18, CGRectGetMaxY(self.coverCollectView.frame) + 220, 50, 20);
        _myPublic_view.remarks_Label.frame = CGRectMake(120, CGRectGetMaxY(self.coverCollectView.frame) + 220, 30, 25);
        _myPublic_view.remarks_textField.frame = CGRectMake(155, CGRectGetMaxY(self.coverCollectView.frame) + 225, kWidth - 155 - 20, 15);
        
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == self.seletedPhotos.count) {
    
        if (self.seletedPhotos.count >= 6) {
            
            [self alertViewShow];
        }
        else {
            [self creatViewPicandPhoto];
        }
    }
}

- (void)creatViewPicandPhoto {
    
    UIAlertController *background_alertController = [UIAlertController alertControllerWithTitle:@"图片上传" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *background_action1 = [UIAlertAction actionWithTitle:@"本地相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //用户相册
        [self pickPhotoButtonClick:nil];
    }];
    UIAlertAction *background_action2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //拍照
        [self takePhotoPicker:UIImagePickerControllerSourceTypeCamera];
    }];
    UIAlertAction *background_action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [background_alertController addAction:background_action1];
    [background_alertController addAction:background_action2];
    [background_alertController addAction:background_action3];
    [self presentViewController:background_alertController animated:YES completion:nil];
}

//拍照
- (void)takePhotoPicker:(UIImagePickerControllerSourceType)sourceType {
    
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = sourceType;
    picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark - imagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [info[UIImagePickerControllerMediaType] isEqualToString:@"public.image"];
    UIImage *headImage_ = info[UIImagePickerControllerOriginalImage];
    [self.seletedPhotos addObjectsFromArray:@[headImage_]];
    [self.coverCollectView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger collectWidth = kWidth - 20;
    NSInteger cellWidth = (collectWidth - 30)/4.f;
    NSInteger height = cellWidth;
    return CGSizeMake(cellWidth , height);
}

- (void)pickPhotoButtonClick:(UIButton *)sender {
    
    NSInteger count = self.seletedPhotos.count;
//    NSLog(@"已经选择的图片：%ld",count);
    self.imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:6-count delegate:self];
    
    __weak typeof (self)weakSelf = self;
    [self.imagePicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets) {
        
        if (weakSelf.seletedPhotos.count < 6) {
            
            [weakSelf.seletedPhotos addObjectsFromArray:photos];
            [weakSelf.coverCollectView reloadData];
        }
        
    }];
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)alertViewShow {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"最多只能添加6张图片" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -- ImagePickerDelegete
- (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    
//    self.viewPic.hidden = YES;
//    [self dismissViewControllerAnimated:YES completion:^{}];
}

//用户选择了原图
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    
    [self.seletedPhotos addObjectsFromArray:@[coverImage]];
    [self.coverCollectView reloadData];
//    self.viewPic.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    switch (component) {
        case 0:
            return _nameArr.count;
            break;
            
        default:
            return 0;
    }
}

#pragma mark UIPickerViewDelegate

- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    switch (component) {
        case 0:
            return _nameArr[row];
            break;
        default:
            return nil;
            break;
    }
}

@end
